<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AccountController extends Controller
{
    /**
     * 获取当前登录用户的信息，没登录时，返回空
     *
     * @param Request $request
     * @return array
     */
    public function show(Request $request)
    {
        $user = $request->user('admin');
        
        $data = empty($user) ? null : [
            'username' => $user->username
        ];
        
        return $this->wrapData($data);
    }
    
    /**
     * 登录
     *
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'password' => 'required',
        ]);
        
        if (! $user = $this->hasValidCredentials($request)) {
            return invalidation(trans('auth.failed'));
        }
        
        return $this->wrapData([
            'username' => $user->username,
            'api_token' => $user->api_token,
        ]);
    }
    
    /**
     * 退出
     *
     * @param Request $request
     */
    public function logout(Request $request)
    {
        $user = $request->user();
        $user->refreshApiToken();
        $user->save();
    }
    
    /**
     * 验证账号、密码是否正确，是的话，返回Admin对象
     *
     * @param Request $request
     * @return bool|Admin
     */
    protected function hasValidCredentials(Request $request)
    {
        $inputs = $request->only('username', 'password');
        $user = Admin::where('username', $inputs['username'])->first();
        
        if (! is_null($user) && Hash::check($inputs['password'], $user->getAuthPassword())) {
            return $user;
        }
        
        return false;
    }

    /**
     * 重设密码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPassword(Request $request)
    {
        $inputs =  $this->validate($request, [
            'old_password' => 'required',
            'new_password' => 'required',
        ]);

        $user = $request->user();

        if (! Hash::check($inputs['old_password'], $user->getAuthPassword())) {
            return access_denied('原密码错误');
        }
        
        $user->update(['password' => bcrypt($inputs['new_password'])]);
    }
}
